# -*- coding: utf-8 -*-
"""
@Time : 2023/6/10 20:00
@Author : Gremore
@File : main
@Des: 
"""


from tsim.register import app, init_logging, register_routers, register_middlewares, create_global_exception_handler
from loguru import logger
from fastapi.middleware.cors import CORSMiddleware
from tsim.core import Events
from tsim.database.redis import sys_cache, code_cache


@app.on_event('startup')
async def startup_event():
    """项目启动时，要做的事情"""
    # 允许跨域请求
    app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])

    # step1 初始化项目日志器
    init_logging()
    logger.info('logging is init success！！！')

    # step2 注册路由
    await register_routers(app)
    logger.info('routers is register success！！！')
    # step3 注册中间件
    await register_middlewares(app)
    logger.info('middlewares is register success！！！')

    # step4 注册全局异常处理器
    await create_global_exception_handler(app)
    logger.info('exceptionHandler is register success！！！')

    from tsim.models import Base, engine
    # step5 向数据库发出建表完成类与表的映射
    logger.info('元数据')
    logger.info(Base.metadata.tables)
    Base.metadata.create_all(engine)
    logger.info('db is init success！！！')

    # 注入缓存到app state
    app.state.cache = await sys_cache()
    app.state.code_cache = await code_cache()


# 事件监听
# app.add_event_handler("startup", Events.startup(app))
app.add_event_handler("shutdown", Events.stopping(app))

